//
//  CoreLocationTool.m
//  消费堡
//
//  Created by Michael on 16/12/9.
//  Copyright © 2016年 Michael. All rights reserved.
//

#import "CoreLocationTool.h"

@interface CoreLocationTool ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;

@property (nonatomic, strong) CLLocation *location;

@property (nonatomic, copy) locationBlock block;

@property (nonatomic, copy) CLGeocodeCompletionHandler completionHandler;

@property (nonatomic, getter=isAuthed) BOOL auth;
@end

@implementation CoreLocationTool


+ (instancetype)shareInstance {
    static CoreLocationTool *shareInstan = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstan = [CoreLocationTool new];
    });
    return shareInstan;
    
}


- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc]init];
        //设置代理
        _locationManager.delegate = self;
    }
    return _locationManager;
}

- (void)getAreaNameCompletionHandler:(CLGeocodeCompletionHandler)completionHandler {
    
    //创建locationManager
    
    self.completionHandler = completionHandler;
    
    if (![CLLocationManager locationServicesEnabled]) {
        // ZCLog(@"定位服务当前可能尚未打开,请设置打开");
        if (self.completionHandler) {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:@"无法定位",NSLocalizedFailureReasonErrorKey:@"用户不同意定位",NSLocalizedRecoverySuggestionErrorKey:@"恢复建议：请打开定位"};
            
            NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:4 userInfo:userInfo];
            self.completionHandler(nil, error);
            
            self.completionHandler = nil;
        }
        return;
    }
    //判断用户是否打开权限
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //打开权限  前台打开定位
        //如果没有授权则提醒用户授权
        //if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
        if (self.isAuthed == YES) {
            [self.locationManager startUpdatingLocation];
        }
        //}
    }else {
        [self.locationManager startUpdatingLocation];
    }
    
    
    
}


- (void)locationWithBlock:(locationBlock)block {
    //创建locationManager
    
    self.block = block;
    
    if (![CLLocationManager locationServicesEnabled]) {
   // ZCLog(@"定位服务当前可能尚未打开,请设置打开");
        if (self.block) {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:@"无法定位",NSLocalizedFailureReasonErrorKey:@"用户不同意定位",NSLocalizedRecoverySuggestionErrorKey:@"恢复建议：请打开定位"};
            
            NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:4 userInfo:userInfo];
            self.block(nil, error);
            
            self.block = nil;
        }
     return;
     }
    //判断用户是否打开权限
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //打开权限  前台打开定位
        //如果没有授权则提醒用户授权
        //if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
        if (self.isAuthed == YES) {
            [self.locationManager startUpdatingLocation];
        }
        //}
    }else {
        [self.locationManager startUpdatingLocation];
    }   

}

//监听用户同意或者不同意
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    //用户同意定位
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        //设置属性
        self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        //100之内不刷新
        //self.locationManager.distanceFilter = 100;
        //打开定位
        self.auth = YES;
        [self.locationManager startUpdatingLocation];
    }else if (status == kCLAuthorizationStatusDenied) {
       // ZCLog(@"用户不同意定位");
        if (self.block) {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:@"无法定位",NSLocalizedFailureReasonErrorKey:@"用户不同意定位",NSLocalizedRecoverySuggestionErrorKey:@"恢复建议：请打开定位"};
            
            NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:4 userInfo:userInfo];
            self.block(nil, error);
            self.block = nil;
        }
        
        if (self.completionHandler) {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:@"无法定位",NSLocalizedFailureReasonErrorKey:@"用户不同意定位",NSLocalizedRecoverySuggestionErrorKey:@"恢复建议：请打开定位"};
            
            NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:4 userInfo:userInfo];
            self.completionHandler(nil, error);
            self.completionHandler = nil;
        }
        
    }
}
//监听用户的位置
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    //获取当前位置
    CLLocation *location = [locations lastObject];
    if (self.block) {
        self.block(location, nil);
        self.block = nil;
    }
    
    //定制定位
    [self.locationManager stopUpdatingLocation];
    
    if (self.completionHandler) {
       CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            
            self.completionHandler(placemarks, error);
            
        }];
        
    }
    

}
//监听用户失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    if (self.block) {
        self.block(nil, error);
        self.block = nil;
    }
    
    if (self.completionHandler) {
        self.completionHandler(nil, error);
        self.completionHandler = nil;
    }
    
}



@end
